package com.easy.robot.framework

import ai.easy.robot.utils.logd
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.Messenger

/**
 * 节点类，订阅和发布消息的主体
 */
open abstract class BaseNode constructor(val name: String, val connector: MasterConnector) {

//    override val name: String
//
//    init {
//        name = name
//    }

    //open fun getName(): String = _name

    abstract protected fun onMessageReceive(topic: String, data: Bundle)

    open protected fun onNodeRegisted() {
        logd("node <$name> registered")
    }

    private val receiver = Messenger(
            object : Handler() {
                override fun handleMessage(msg: Message?) {
                    logd("msg>>")
                    when (msg?.what) {
                        MasterService.NODE_MSG -> onMessageReceive("${msg.obj}", msg?.data)
                        MasterService.NODE_MSG_ON_REG -> onNodeRegisted()
                        else -> {
                        }
                    }
                }
            })

    fun register() {
        val m = Message.obtain()
        m.what = MasterService.NODE_MGR_REG
        m.obj = name
        m.replyTo = receiver
        connector.messenger?.send(m)
    }

    fun unregister() {
        val m = Message.obtain()
        m.what = MasterService.NODE_MGR_UN_REG
        m.obj = name
        connector.messenger?.send(m)
    }

    fun subscribe(topic: String) {
        val m = Message.obtain()
        m.what = MasterService.NODE_MSG_SUB
        m.obj = arrayOf(name, topic)
        connector.messenger!!.send(m)
    }

    fun publish(topic: String, msg: Bundle) = connector.publish(topic, msg)
}